from fastapi import HTTPException


class View:
    """公共视图"""
    ExportSchema = ''

    @classmethod
    def _import(cls, session, data):
        try:
            cls.create_item(session, data)
        except Exception as e:
            return {'id': data['id'], 'error': '数据写入失败'}

    @classmethod
    def _export_format(cls, datas):
        return [cls.ExportSchema(**item) for item in datas]

    @classmethod
    def export(cls, session, ids):
        datas = cls.get_items(session, filter_=[cls.id.in_(ids)] if ids is not None else None).all()
        return cls._export_format(datas)

    @classmethod
    def import_(cls, session, datas, ignore_errors=True):
        ids = [data['id'] for data in datas]  # 导入数据
        ids_ = [item.id for item in session.query(cls).filter(cls.id.in_(ids))]  # 数据库内数据
        if ids_:
            if not ignore_errors:
                raise HTTPException(status_code=400, detail='数据库中包含重复数据')
            
        errors = []
        for data in datas:
            if data['id'] in ids_:
                errors.append({'id': data['id'], 'error': '数据已存在'})
                continue
            
            error = cls._import(session, data)  # 导入数据
            if error:
                errors.append(error)
        return errors
